import { fabric } from 'fabric';

import ObjectPool from './ObjectPool';

// 创建六边形的点
const createHexagonPoints = (size = 50) => {
  const angle = Math.PI / 3; // 60度
  const points = [];
  for (let i = 0; i < 6; i++) {
    const x = size * Math.cos(i * angle);
    const y = size * Math.sin(i * angle);
    points.push({ x, y });
  }
  return points;
};

class Hexagon extends fabric.Polygon {
  constructor(options = {}) {
    const points = [
      { x: 25, y: -43.3 },      // 右上
      { x: 50, y: 0 },          // 右
      { x: 25, y: 43.3 },       // 右下
      { x: -25, y: 43.3 },      // 左下
      { x: -50, y: 0 },         // 左
      { x: -25, y: -43.3 },     // 左上
    ];

    super(points, {
      fill: '#1abc9c',
      strokeWidth: 1,
      stroke: '#000000',
      selectable: true,
      cornerSize: 10,
      transparentCorners: false,
      hasRotatingPoint: true,
      padding: 5,
      id: '',  // 添加id属性
      ...options,
    });

    // 确保控制点颜色与边框颜色一致
    this.set({
      cornerColor: this.stroke,
      borderColor: this.stroke,
    });

    // 添加阴影效果
    this.set(
      'shadow',
      new fabric.Shadow({
        color: 'rgba(0,0,0,0.15)',
        blur: 5,
        offsetX: 3,
        offsetY: 3,
      }),
    );
  }

  // 更新属性
  updateProps(props) {
    if (props.size) {
      const points = createHexagonPoints(props.size);
      this.set('points', points);
    }

    this.set(props);

    // 如果更新了边框颜色，同时更新控制点颜色
    if (props.stroke) {
      this.set({
        cornerColor: props.stroke,
        borderColor: props.stroke,
      });
    }

    this.canvas?.requestRenderAll();
    return this;
  }

  // 设置大小
  setSize(size) {
    this.updateProps({ size });
    return this;
  }

  // 移到顶层
  bringToFront() {
    if (this.canvas) {
      this.canvas.bringToFront(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 移到底层
  sendToBack() {
    if (this.canvas) {
      this.canvas.sendToBack(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 删除自身
  remove() {
    if (this.canvas) {
      this.canvas.remove(this);
      this.canvas.requestRenderAll();
    }
  }
}

// 创建一个全局的六边形对象池
const hexagonPool = new ObjectPool(() => new Hexagon());

// 导出Hexagon类和hexagonPool
export { Hexagon, hexagonPool };
export default Hexagon;
